﻿using MPI;
using System;

namespace ParallelLib
{
    partial class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            MpiWorker worker = new MpiWorker();
            MPI.Environment.Run(ref args, MpiWork);
            worker.StartPoller();
        }

        private static void MpiWork(Intracommunicator comm)
        {
            if (comm.Rank == 0)
            {
                Console.WriteLine("Rank 0 is alive and running on " + MPI.Environment.ProcessorName);
                while (true)
                {
                    Console.WriteLine("Ready Input CMD...\n" + comm.Size + "\n");
                    var cmd = Console.ReadLine();
                    SendCmd(comm, cmd);
                    if (cmd == "exit")
                        break;
                }
            }
            else
            {
                while (true)
                {
                    Console.WriteLine("Waiting CMD...");
                    var str = comm.Receive<string>(0, 0);
                    Debug("{0}-收到消息:{1}", MPI.Environment.ProcessorName, str);
                    switch (str)
                    {
                        case "exit":
                            comm.Send(MPI.Environment.ProcessorName + "_Exit", 0, 1);
                            break;
                        default:
                            var msg = MPI.Environment.ProcessorName + "****已收到消息" + str;
                            comm.Send(msg, 0, 1);
                            Debug("{0}-已发送消息:【{1}】", MPI.Environment.ProcessorName, msg);
                            break;
                    }
                }
            }
        }

        private static void Debug(string msg)
        {
            System.Diagnostics.Trace.WriteLine(msg);
        }
        private static void Debug(string format, params object[] s)
        {
            var msg = string.Format(format, s);
            System.Diagnostics.Trace.WriteLine(msg);
        }
        private static void SendCmd(Intracommunicator comm, string cmd)
        {
            for (int dest = 1; dest < comm.Size; ++dest)
            {
                Console.Write("Pinging process with rank " + dest + "...");
                //comm.Send("Ping!", dest, 0);
                comm.Send(cmd, dest, 0);
                string destHostname = comm.Receive<string>(dest, 1);
                //Console.WriteLine(" Pong!");
                Console.WriteLine("  Rank " + dest + " is alive and running on " + destHostname);
            }
        }
    }
}
